require('dotenv').config();
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors');
var helmet = require('helmet');
var compression = require('compression');
var rateLimit = require('express-rate-limit');

// Import route modules
var indexRouter = require('./routes/index');
var authRouter = require('./routes/auth');
var homeRouter = require('./routes/home');
var studyRouter = require('./routes/study');
var detectionRouter = require('./routes/detection');
var gameRouter = require('./routes/game');
var dailyRouter = require('./routes/daily');
var notificationsRouter = require('./routes/notifications');
var statisticsRouter = require('./routes/statistics');
var uploadRouter = require('./routes/upload');
var usersRouter = require('./routes/users');
var coursesRouter = require('./routes/courses');
var healthRouter = require('./routes/health');

var app = express();

// Security middleware
app.use(helmet());
app.use(cors({
  origin: process.env.ALLOWED_ORIGINS ? process.env.ALLOWED_ORIGINS.split(',') : ['http://localhost:3000'],
  credentials: true
}));

// Rate limiting
const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100, // limit each IP to 100 requests per windowMs
  message: {
    code: 429,
    message: '请求过于频繁，请稍后再试',
    timestamp: Date.now()
  }
});
app.use('/api/', limiter);

// Compression middleware
app.use(compression());

// Basic middleware
app.use(logger('dev'));
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ extended: false, limit: '50mb' }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// API routes
app.use('/', indexRouter);
app.use('/auth', authRouter);
app.use('/home', homeRouter);
app.use('/study', studyRouter);
app.use('/detection', detectionRouter);
app.use('/game', gameRouter);
app.use('/daily', dailyRouter);
app.use('/notifications', notificationsRouter);
app.use('/statistics', statisticsRouter);
app.use('/upload', uploadRouter);
app.use('/users', usersRouter);
app.use('/courses', coursesRouter);
app.use('/health', healthRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// Global error handler
app.use(function(err, req, res, next) {
  // Set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // Send JSON response for API routes
  if (req.path.startsWith('/api/') || req.path.startsWith('/auth') ||
      req.path.startsWith('/home') || req.path.startsWith('/study') ||
      req.path.startsWith('/detection') || req.path.startsWith('/game') ||
      req.path.startsWith('/daily') || req.path.startsWith('/notifications') ||
      req.path.startsWith('/statistics') || req.path.startsWith('/upload') ||
      req.path.startsWith('/users') || req.path.startsWith('/courses') ||
      req.path.startsWith('/health')) {
    return res.status(err.status || 500).json({
      code: err.status || 500,
      message: err.message || '服务器内部错误',
      timestamp: Date.now()
    });
  }

  // Render error page for other routes
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
